app.controller('RepairCtrl', ['$scope', '$q', '$timeout', 'apiService',
    function(scope, $q, $timeout, apiService) {
		
		scope.products = [];
		
		var init = function() {
			loadMember();
			loadProducts(1);
		};
		
		var loadMember = function() {
			apiService.get("/api/member").then(function(resp){
				if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
					scope.member = resp.data.data;
				} else {
					// todo
				}
			}, function(error){
				console.log(error);
			});
		};
		
		var loadProducts = function(pageIndex){
			apiService.get("/api/repair?pageIndex="+pageIndex).then(function(resp){
				if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
					var data = resp.data.data;
					if (data.products && data.products.length) {
						scope.products = scope.products.concat(data.products.filter(function(i){return i.regStatus == 1 && (!i.weStatus || i.weStatus == 0 || i.weStatus == 1);}));
					}
					
					if (data && data.page_total > data.page_index) {
						$timeout(function(){loadProducts(data.page_indxe + 1);}, 5000);
					}
				} else {
					
				}
			}, function(error){
				console.log(error);
			});
		};
		
		scope.applyExtend = function(product) {
			if (!scope.member || !scope.member.tel) {
				$('.alert-error button').click(function(){
					window.location.href = "https://siemens.ews.m.jaeapp.com/profile/"+$("#stid").val();
				});
				showErrorMsg("请先完善个人信息");
				return;
			}
			apiService.put("/api/warranty/"+product.lcs_id).then(function(resp){
				if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
					var data = resp.data.data;
					product.weStatus = data.weStatus;
					product.weCodes = data.weCodes;
					product.weExpDT = data.weExpDT;
					showMsg("延保成功");
				} else {
					if (resp && resp.data && resp.data.meta && resp.data.meta.errors && resp.data.meta.errors.length && resp.data.meta.errors[0]
						&& resp.data.meta.errors[0].msg) {
						showErrorMsg(resp.data.meta.errors[0].msg);
					} else {
						showErrorMsg("系统正忙，请稍后再试");
					}
				}
			}, function(error){
				showErrorMsg("系统正忙，请稍后再试.");
			});
		};
		
		var showMsg = function(msg) {
			scope.msg = msg;
			if ($('.alert').hasClass('hide')) {
				$('.alert').removeClass('hide');
			}
		};
		
		var showErrorMsg = function(msg) {
			scope.msg = msg;
			if ($('.alert-error').hasClass('hide')) {
				$('.alert-error').removeClass('hide');
			}
		};
		
		init();
	}
]);

$('.alert button,.alert-error button').click(function(){
    if(!$('.alert').hasClass('hide')){
      $('.alert').addClass('hide');
    }
    if(!$('.alert-error').hasClass('hide')){
      $('.alert-error').addClass('hide');
    }
  });
